<?php

namespace app\api\controller;


use app\common\controller\Api;
use think\facade\Request;

/**
 * 图灵sdk
 */
class Turingos extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    private $get_unique_uid="https://api.turingos.cn/getuserid.do";
    private $url="http://api.turingos.cn/turingos/api/v2";
    private $ttsurl="http://smartdevice.ai.turingapi.com/speech/v2/tts";
    private $asrurl="http://smartdevice.ai.turingapi.com/speech/v2/asr";
    private $apiKey = '';
    private $wifiapiKey = '020618c9d9d44aaca72845377fc0db36';
    private $wifiapiSecret = '33qpD90xT042TALd';

    public function __construct()
    {
        parent::__construct();
        $this->apiKey = '0e478014007840208eb05a4e6e159d35';
    }

    public function index($text='望庐山瀑布')
    {
        $getuid = $this->get_char_id();
        $uid = session('tulingos_uid');
        $data = [
            "data"=>[
                "content"=>[
                    ["data"=>$text]
                ],
                "userInfo"=>[
                    "uniqueId"=>$uid
                ]
            ],
            'key'=>$this->apiKey,
            'timestamp'=>time()
        ];
        $res = $this->postCurl($this->url,$data);

        if($res["code"]!=200){
            $this->error('请检查图灵匹配设置,错误码为：'.$res["data"]["intent"]["code"]);
        }
        if($res["data"]["intent"]["code"]==100302){
            return
                [
                    'code'=>1,
                    'data'=>['title'=>$res["data"]["results"][0]["values"]['text']]

                ];exit();
        }else{
            return
                [
                    'code'=>0,
                    'data'=>['title'=>$res["data"]["results"][0]["values"]['text']]

                ];exit();
            $this->error('知识库未匹配到');
        }
    }

    public function get_char_id(){
//如果用户还没有临时对话变量，则注册一个 $_SESSION['char_id']
        if(!isset($_SESSION['tulingos_uid']) ){
            $url = "https://api.turingos.cn/getuserid.do";
            $data = [
                "data" => [
                    "uniqueId"=>"ai12345678910"
                ],
                "key" =>$this->apiKey,
                'timestamp'=>time()
            ];
            $res = $this->postCurl($url, $data);
            if($res['code']==200){
                session('tulingos_uid',$res['data']['userid']);
            }else{
                $this->error('授权设备失败');
            }
        }
    }

    function postCurl($url,$data, $type = "POST",$content_type='application/json',$is_json=true){
        if($is_json){
            $data  = json_encode($data);
        }
        $headerArray =array("Content-type:".$content_type);
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,FALSE);
//        curl_setopt($curl, CURLOPT_POST, 1);
        switch ($type) {
            case "GET":
                curl_setopt($curl, CURLOPT_HTTPGET, true);
                break;
            case "POST":
                curl_setopt($curl, CURLOPT_POST, true);
                break;
            case "PUT"://使用一个自定义的请求信息来代替"GET"或"HEAD"作为HTTP请									                     求。这对于执行"DELETE" 或者其他更隐蔽的HTT
                curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
                break;
            case "DELETE":
                curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE");
                break;
        }
        //设置请求方法
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl,CURLOPT_HTTPHEADER,$headerArray);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        $httpCode = curl_getinfo($curl,CURLINFO_HTTP_CODE);
        curl_close($curl);
        $return_data = [
            "data" => json_decode($output,true),
            "code" => $httpCode
        ];
        return $return_data;

    }

    public function speechasr($deviceId='1800000000000000',$file){
        $config=[
            'key'	=>	$this->wifiapiSecret, //appsecret
            'iv'	=>  substr($this->wifiapiKey , 0 , 16), //ApiKey前16个字符作为密钥偏移量
            'method'	=> 'AES-128-CBC' //加密方式  # AES-128-CBC等
        ];
        $aes = new Aes($config);
        $uid = $aes->aesEn($deviceId);//加密数据deviceId16
        $token = session('awifitoken');
        /*$file = $_FILES['file'];*/
        $parameters = '{"ak": "'.$this->wifiapiKey.'","uid": "'.$uid.'","asr": 0,"token": "'.$token.'"}';
        $data = [
            'parameters'=>$parameters,
            'speech' => new \CURLFile(realpath($file["tmp_name"]), $file["type"], $file["name"])
        ];
        $res = $this->postCurl($this->asrurl,$data,'POST','multipart/form-data',false);
        if($res["code"]!=200){
            $this->error('请检查图灵awifi设置,错误码为：'.$res["code"]);
        }
        if($res["data"]["code"]==220){
            session('awifitoken',$res["data"]['token']);
            $this->success('语音转文字成功', ['text'=>$res["data"]["text"]]);
        }else{
            $this->error('参数有误'.$res["data"]["code"]);
        }
    }

    //文字转语音
    public function speechtts($deviceId='1800000000000000',$msg="我是默认文本"){
        $config=[
            'key'	=>	$this->wifiapiSecret, //appsecret
            'iv'	=>  substr($this->wifiapiKey , 0 , 16), //ApiKey前16个字符作为密钥偏移量
            'method'	=> 'AES-128-CBC' //加密方式  # AES-128-CBC等
        ];
        $aes = new Aes($config);
        $uid = $aes->aesEn($deviceId);//加密数据deviceId16
        $token = session('awifitoken');
        $data['parameters'] = [
            'ak'=>$this->wifiapiKey,
            'uid'=>$uid,
            'token'=>empty($token)?'':$token,
            'text'=>$msg,
            'tone'=>22,
            'tts'=>3
        ];
        $res = $this->postCurl($this->ttsurl,$data);
        if($res["code"]!=200){
            $this->error('请检查图灵awifi设置,错误码为：'.$res["code"]);
        }
        if($res["data"]["code"]==200){
            session('awifitoken',$res["data"]['token']);
            $this->success('获取成功', ['url'=>$res["data"]["url"]]);
        }else{
            $this->error('参数有误'.$res["data"]["code"]);
        }
    }

}
